package com.wangtongxiao.controller;
import com.wangtongxiao.beans.User;
import com.wangtongxiao.dto.ResuDTO;
import com.wangtongxiao.exception.Loginexception;
import com.wangtongxiao.services.UserServices;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    @Qualifier("userServices")
    UserServices userServices;

    @RequestMapping("in.action")
    public ResuDTO in(HttpSession session, HttpServletResponse response, String loginAct, String loginPwd, String rememberMe) throws Loginexception {
        User login = userServices.login(loginAct, loginPwd);
        if (login == null) {
            throw new Loginexception("用户账号或密码错误");
        }
//        登陆成功
        session.setAttribute("user", login);
//设置键值对，必须是String类型
        Cookie cookieLoginAct = new Cookie("loginAct", loginAct);
        //            设置键值对的作用域，
        cookieLoginAct.setPath("/");
        Cookie cookieLoginPwd = new Cookie("loginPwd", DigestUtils.md5Hex(loginPwd));
        cookieLoginPwd.setPath("/");
        if (rememberMe.equals("true")) {
//            设置年龄
            cookieLoginAct.setMaxAge(60 * 60);
            cookieLoginPwd.setMaxAge(60 * 60);
        } else {
            cookieLoginAct.setMaxAge(0);
            cookieLoginPwd.setMaxAge(0);
        }
        //相应添加浏览器值
        response.addCookie(cookieLoginAct);
        response.addCookie(cookieLoginPwd);

        ResuDTO resuDTO = new ResuDTO();
        resuDTO.setResult(ResuDTO.SUCCESS);
        resuDTO.setData(login);
        return resuDTO;
    }

    @RequestMapping("userInfo.action")
    public ResuDTO userInfo(HttpSession httpSession) throws Loginexception {
        ResuDTO resuDTO = new ResuDTO();
        resuDTO.setResult(ResuDTO.SUCCESS);
        Object login = httpSession.getAttribute("user");

        if (login == null) {
            throw new Loginexception("请登录");
        }
        resuDTO.setData(login);
        return resuDTO;
    }

    @RequestMapping("out.action")
    public ResuDTO btnLogout(HttpSession httpSession,HttpServletResponse response) {
        httpSession.removeAttribute("user");
//        删除Cookie
        Cookie cookie = new Cookie("loginAct","");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        Cookie cookie1 = new Cookie("loginPwd","");
        cookie1.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        response.addCookie(cookie1);



        ResuDTO resuDTO = new ResuDTO();
        resuDTO.setResult(ResuDTO.SUCCESS);
        return resuDTO;


    }

}
